Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports DotNetNuke.Entities.Portals
Imports DotNetNuke.Modules.ProjectTracker
Imports DotNetNuke.Modules.ProjectTracker.Business

Namespace DotNetNuke.Modules.ProjectTracker

    Public MustInherit Class ProjectTracker
        Inherits Entities.Modules.PortalModuleBase
        Implements Entities.Modules.IActionable
        Implements Entities.Modules.IPortable
        Implements Entities.Modules.ISearchable
        Const INT_FAILED As Integer = -2

#Region "Controls"

        Protected WithEvents lblDescription As System.Web.UI.WebControls.Label
        Protected WithEvents pnlModuleContent As System.Web.UI.WebControls.Panel
        Protected WithEvents ddlFilter As System.Web.UI.WebControls.DropDownList
        Protected WithEvents myDataGrid As System.Web.UI.WebControls.DataGrid
        Protected WithEvents lbSubmit As System.Web.UI.WebControls.LinkButton

#End Region

#Region "Private Members"

        Private _portalSettings As PortalSettings
        Private m_HistoryInfo As HistoryInfo
        Private m_HistoryController As New HistoryController
        Private m_utils As New DotNetNuke.Modules.ProjectTracker.Utils

#End Region

#Region "Event Handlers"

        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim objRoleController As New DotNetNuke.Security.Roles.RoleController
            Dim objUserController As New DotNetNuke.Entities.Users.UserController
            Dim objUser As UserInfo
            Dim _authRoles As String = ""

            ' Obtain PortalSettings from Current Context
            _portalSettings = CType(HttpContext.Current.Items("PortalSettings"), PortalSettings)

            Try
                If Not Page.IsPostBack Then

                    BindDataGrid("OPEN")
                    lblDescription.Text = CType(Settings("description"), String)

                    ' check to see if the current user is a member of the authorized roles
                    ' for the 1st state. if so, then enable the Submit Package link
                    Dim bCanSubmit As Boolean = False
                    Try
                        Dim sController As New StatesController
                        Dim states As ArrayList = sController.GetStatesList(ModuleId)
                        Dim sInfo As StatesInfo = CType(states(0), StatesInfo)
                        If Not sInfo Is Nothing Then
                            For Each RoleId As String In sInfo.AuthorizedRoles.Split(CType(";", Char))
                                ' get list of role members
                                If RoleId <> "-1" And RoleId <> "" Then
                                    Dim RoleName As String = objRoleController.GetRole(Integer.Parse(RoleId), _portalSettings.PortalId).RoleName
                                    _authRoles += (RoleName & ";")
                                End If
                            Next
                        End If
                        If _authRoles.Length > 0 Then
                            _authRoles = _authRoles.TrimEnd(CType(";", Char))
                        End If
                        If Security.PortalSecurity.IsInRoles(_authRoles) Then
                            bCanSubmit = True
                        End If
                    Catch ex As Exception
                    End Try

                    lbSubmit.Visible = bCanSubmit

                End If
            Catch exc As Exception
                ProcessModuleLoadException(Me, exc)
            End Try

        End Sub

        Private Sub lbSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lbSubmit.Click
            Response.Redirect(EditUrl())
        End Sub

        Private Sub SetCellBackgrounds(ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs, ByVal className As String)
            For i As Integer = 1 To 12
                e.Item.Cells(i).CssClass = className
            Next
        End Sub
        Private Sub myDataGrid_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles myDataGrid.ItemDataBound

            If e.Item.ItemType = ListItemType.Header Then
                If CType(Settings("LastActivityOnGrid"), Boolean) Then
                    e.Item.Cells(5).Text = "Project Name/Last Activity"
                Else
                    e.Item.Cells(5).Text = "Project Name"
                End If
            End If

            If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then

                Dim userController As New DotNetNuke.Entities.Users.UserController
                Dim userInfo As DotNetNuke.Entities.Users.UserInfo

                Dim projectController As New ProjectsController
                Dim project As ProjectsInfo = projectController.GetProjectsInfo(Integer.Parse(e.Item.Cells(2).Text))

                ''' lookup the project lead
                userInfo = Nothing
                userInfo = userController.GetUser(PortalId, Integer.Parse(e.Item.Cells(8).Text))
                If Not userInfo Is Nothing Then
                    e.Item.Cells(8).Text = userInfo.DisplayName
                End If

                ''' lookup the project chair
                userInfo = Nothing
                userInfo = userController.GetUser(PortalId, Integer.Parse(e.Item.Cells(9).Text))
                If Not userInfo Is Nothing Then
                    e.Item.Cells(9).Text = userInfo.DisplayName
                End If

                ' place the timespan since the lasty activity under the project name
                Dim history As ArrayList = m_HistoryController.GetHistoryList(project.ItemID)
                If history.Count > 0 Then
                    m_HistoryInfo = CType(history(history.Count - 1), HistoryInfo)
                    Dim ts As TimeSpan = Date.Now.Subtract(m_HistoryInfo.CreatedDate)
                    If CType(Settings("LastActivityOnGrid"), Boolean) Then
                        e.Item.Cells(5).Text &= "<br><span class='tiny'>" & m_utils.FormatTimeSpan(ts) & "</span>"
                    End If
                    If CType(Settings("ColorCodeGrid"), Boolean) And project.Status = "OPEN" Then
                        If ts.Days < 10 Then
                            SetCellBackgrounds(e, "ptGridGreen")
                        Else
                            If ts.Days < 30 Then
                                SetCellBackgrounds(e, "ptGridYellow")
                            Else
                                SetCellBackgrounds(e, "ptGridRed")
                            End If
                        End If
                    End If
                End If

                ''' lookup the current state
                If e.Item.Cells(11).Text = "0" Then
                    ' 0 = not started yet
                    e.Item.Cells(11).Text = ""
                Else
                    ' anything else represents the current state
                    Dim stateController As New StatesController
                    Dim stateInfo As StatesInfo = stateController.GetStatesInfo(Integer.Parse(e.Item.Cells(11).Text))
                    Dim states As ArrayList = stateController.GetStatesList(ModuleId)
                    Dim i As Integer
                    Dim t_state As StatesInfo
                    Dim t_status As String = ""

                    Dim _count As Integer = states.Count
                    Dim _rating As Integer = 0

                    Dim stateChanged As Boolean = False
                    i = 0
                    While i < states.Count
                        t_state = CType(states(i), StatesInfo)
                        If t_state.ItemID = stateInfo.ItemID Then
                            _rating = i
                        End If
                        i = i + 1
                    End While

                    Dim img As New Image
                    Dim img2 As New Image

                    If _count > 0 Then
                        Select Case project.Status
                            Case "OPEN"
                                img.ImageUrl = String.Format("~/DesktopModules/ProjectTracker/images/GraphicsProcessor.aspx?f=RatingImage&image=grey.jpg&selected=green.jpg&rating={0}&count={1}", _rating, _count)
                            Case "COMPLETE"
                                img.ImageUrl = String.Format("~/DesktopModules/ProjectTracker/images/GraphicsProcessor.aspx?f=RatingImage&image=grey.jpg&selected=green.jpg&rating={0}&count={1}", _count, _count)
                            Case "FAILED"
                                img.ImageUrl = String.Format("~/DesktopModules/ProjectTracker/images/GraphicsProcessor.aspx?f=RatingImage&image=grey.jpg&selected=red.jpg&rating={0}&count={1}", _rating, _count)
                        End Select
                    Else
                        img.ImageUrl = "~/DesktopModules/ProjectTracker/images/spacer.gif"
                    End If
                    e.Item.Cells(11).Controls.Add(img)

                    e.Item.Cells(12).Text = ""

                    _count = 0
                    _rating = 0
                    Dim m_ecController As New ExitCriteriaController
                    For Each ecInfo As ExitCriteriaInfo In m_ecController.GetExitCriteriaList(stateInfo.ItemID)
                        _count = _count + 1
                        m_HistoryInfo = Nothing
                        m_HistoryInfo = m_HistoryController.GetHistoryActivityByType(project.ItemID, "EXITCRITERIA", ecInfo.ItemID)
                        If Not m_HistoryInfo Is Nothing Then
                            _rating = _rating + 1
                        End If
                    Next

                    If _count > 0 Then
                        If project.Status = "OPEN" Then
                            img2.ImageUrl = String.Format("~/DesktopModules/ProjectTracker/images/GraphicsProcessor.aspx?f=RatingImage&image=grey.jpg&selected=green.jpg&rating={0}&count={1}", _rating, _count)
                        Else
                            img2.ImageUrl = "~/DesktopModules/ProjectTracker/images/spacer.gif"
                        End If
                    Else
                        img2.ImageUrl = "~/DesktopModules/ProjectTracker/images/spacer.gif"
                    End If
                    e.Item.Cells(12).Controls.Add(img2)

                End If

            End If

        End Sub

        Private Sub myDataGrid_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles myDataGrid.ItemCommand

            Dim projController As New ProjectsController
            Dim projInfo As ProjectsInfo
            Dim strFilename As String
            If e.CommandName = "download" Then
                projInfo = projController.GetProjectsInfo(Integer.Parse(e.Item.Cells(2).Text))
                If Not projInfo Is Nothing Then
                    strFilename = context.Server.MapPath("~/Portals/" & PortalSettings.PortalId & "/Projects") & "/" & projInfo.Url
                    DotNetNuke.Common.Utilities.FileSystemUtils.DownloadFile(strFilename)
                End If
            End If

        End Sub

        Private Sub ddlFilter_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlFilter.SelectedIndexChanged
            BindDataGrid(ddlFilter.SelectedValue)
        End Sub

        Private Sub BindDataGrid(ByVal filter As String)
            Dim objProjectTracker As New ProjectsController
            Dim list As ArrayList
            list = objProjectTracker.GetProjectsList(ModuleId, filter)
            myDataGrid.DataSource = list
            myDataGrid.DataBind()
        End Sub

#End Region

#Region "Optional Interfaces"
        Public ReadOnly Property ModuleActions() As Entities.Modules.Actions.ModuleActionCollection Implements Entities.Modules.IActionable.ModuleActions
            Get
                Dim Actions As New Entities.Modules.Actions.ModuleActionCollection
                ' Actions.Add(GetNextActionID, Localization.GetString(Entities.Modules.Actions.ModuleActionType.AddContent, LocalResourceFile), Entities.Modules.Actions.ModuleActionType.AddContent, "", "", EditUrl(), False, DotNetNuke.Security.SecurityAccessLevel.Edit, True, False)
                Actions.Add(GetNextActionID, Localization.GetString("Setup", LocalResourceFile), "Setup", "", "", EditUrl("Setup"), False, DotNetNuke.Security.SecurityAccessLevel.Admin, True, False)
                Actions.Add(GetNextActionID, Localization.GetString("Metrics", LocalResourceFile), "Metrics", "", "", EditUrl("Metrics"), False, DotNetNuke.Security.SecurityAccessLevel.Admin, True, False)
                Actions.Add(GetNextActionID, Localization.GetString("About", LocalResourceFile), "About", "", "", EditUrl("About"), False, DotNetNuke.Security.SecurityAccessLevel.Edit, True, False)
                Return Actions
            End Get
        End Property

        Public Function ExportModule(ByVal ModuleID As Integer) As String Implements Entities.Modules.IPortable.ExportModule
            ' included as a stub only so that the core knows this module Implements Entities.Modules.IPortable
        End Function

        Public Sub ImportModule(ByVal ModuleID As Integer, ByVal Content As String, ByVal Version As String, ByVal UserID As Integer) Implements Entities.Modules.IPortable.ImportModule
            ' included as a stub only so that the core knows this module Implements Entities.Modules.IPortable
        End Sub

        Public Function GetSearchItems(ByVal ModInfo As Entities.Modules.ModuleInfo) As Services.Search.SearchItemInfoCollection Implements Entities.Modules.ISearchable.GetSearchItems
            ' included as a stub only so that the core knows this module Implements Entities.Modules.ISearchable
        End Function

#End Region

#Region " Web Form Designer Generated Code "

        'This call is required by the Web Form Designer.
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

        End Sub

        'NOTE: The following placeholder declaration is required by the Web Form Designer.
        'Do not delete or move it.
        Private designerPlaceholderDeclaration As System.Object

        Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
            'CODEGEN: This method call is required by the Web Form Designer
            'Do not modify it using the code editor.
            InitializeComponent()
        End Sub


#End Region

    End Class

End Namespace
